package com.palmshop.online.alipay.util;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.jdbc.core.JdbcTemplate;
/**
 * AlipayCallback <br>
 * 支付宝支付通知接口（后台接口）
 * <p>
 * Copyright: Copyright (c) 2012-3-11 上午10:06:08
 * 
 * @author kongjp@c-platform.com
 * @version 1.0.0
 */
@WebServlet(name = "AlipayCallback", urlPatterns = { "/AlipayCallback.do" })
public class AlipayCallback extends HttpServlet {
	@Resource
	private static JdbcTemplate template;
	/**
	 * serialVersionUID:TODO（用一句话描述这个变量表示什么）
	 * 
	 * @since Ver 1.1
	 */

	private static final long serialVersionUID = -5436836477374478338L;

	@Override
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		System.out.println("controller:"+"!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
		
		
		
		// 1. 获取支付宝POST的通知报文
		Map<String, String> params = new HashMap<String, String>();
		Map requestParams = request.getParameterMap();
		String req = "";
		try {
			for (Iterator iter = requestParams.keySet().iterator(); iter
					.hasNext();) {

				String name = (String) iter.next();
				String[] values = (String[]) requestParams.get(name);

				String valueStr = "";
				for (int i = 0; i < values.length; i++) {
					valueStr = (i == values.length - 1) ? valueStr + values[i]
							: valueStr + values[i] + ",";
				}
				params.put(name, valueStr);
				req += name + "=" + valueStr + "&";
			}
			new AlipayCore().logResult(" 【 alipay 服务器异步通知 】 报文： " + req);
			System.out.println(" 【 alipay 服务器异步通知 】 报文： " + req);
		} catch (Exception e) {
			e.printStackTrace();
		}
		/*
		 * if (params == null) return;
		 */
		// 2. 获取支付宝的通知返回参数
		String order_no = params.get("out_trade_no"); // 解析订单号
		
		

		String trade_status = request.getParameter("trade_status"); // 交易状态
		// 3. 校验通知报文，更新支付订单状态
		if (AlipayNotify.verify(params)) {
			// 判断订单状态
			if (trade_status.equals("TRADE_SUCCESS")) {
				// 交易成功通知，更新支付完成的商户业务逻辑
				boolean rslt = processPayFisish(order_no);
				if (rslt) {
					new AlipayCore().logResult("【alipay 服务器异步通知】 支付宝通知处理成功！1");
					System.out.println("【alipay 服务器异步通知】 支付宝通知处理成功！");
					createResp("success", response);
				} else {
					new AlipayCore().logResult("【alipay 服务器异步通知】 支付宝通知处理失败！1");
					System.out.println("【alipay 服务器异步通知】 支付宝通知处理失败！");
					createResp("fail", response);
				}
			} else if (trade_status.equals("TRADE_FINISHED")) {
				// 过了签约时的可退款时限通知（如：三个月以内可退款、一年以内可退款等）
				new AlipayCore().logResult("【alipay 服务器异步通知】 支付宝通知验证成功！2");
				System.out.println("【alipay 服务器异步通知】 支付宝通知验证成功！");
				createResp("success", response);
			} else {
				// 验证失败
				new AlipayCore().logResult("3【alipay 服务器异步通知】 支付宝通知异常，status: "
						+ trade_status);
				System.out.println("【alipay 服务器异步通知】 支付宝通知异常，status: "
						+ trade_status);
				createResp("fail", response);
			}

		} else {
			new AlipayCore().logResult("【alipay 服务器异步通知】 签名验证失败! 3");
			System.out.println("【alipay 服务器异步通知】 签名验证失败! ");
			createResp("fail", response);
		}
	}

	/**
	 * 
	 * 
	 * processPayFisish(<处理业务逻辑>)
	 * 
	 * TODO(这里描述这个方法适用条件 – 可选)
	 * 
	 * @param name
	 * 
	 * @param @return 设定文件
	 * 
	 * @return String DOM对象
	 * 
	 * @Exception 异常对象
	 * 
	 * @since CodingExample　Ver(编码范例查看) 1.1
	 */
	private static boolean processPayFisish(String orderNo) {
		if (orderNo != null && !"".equals(orderNo)) {
			String sql = "UPDATE FROM donation SET donation_state=1  WHERE donation_serial_number=?";
			Integer status = template.update(sql, orderNo);
			if (status != 0) {
				return true;
			}

		}
		return false;
	}

	@Override
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

	private void createResp(String str, HttpServletResponse response) {
		try {
			response.setContentType("text/plain");
			response.setCharacterEncoding("utf-8");
			PrintWriter out = response.getWriter();
			out.println(str);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
